import BaseConfig, { IItemConfig } from "../../../Script/Base/BaseConfig";
import BaseView from "../../../Script/Base/BaseView";
import { EBagType, EBundleType, EDropType, EResType, EViewType } from "../../../Script/Common/Enum";
import EventID from "../../../Script/Common/EventID";
import { GlobalData, ICollectConfig } from "../../../Script/Common/GlobalData";
import { TalkModule } from "../../../Script/Common/TalkModule";
import { IBaseSkeData, IGameData, IMessage, ITalkData, IViewData } from "../../../Script/Interface/IMessage";
import { SceneGame } from "../../../Script/SceneGame";
import AppService from "../../../Script/Service/AppService";
import GameUtil from "../../../Script/Util/GameUtil";
import { LoadUtil } from "../../../Script/Util/LoadUtil";
import StorageUtil from "../../../Script/Util/StorageUtil";
import { AdManager } from "../../naodong/ads/AdManager";
import AudioManager from "../../Util/AudioManager";
import GameUI from "../GameUI";
import TownUI from "../town/TownUI";

const { ccclass, property } = cc._decorator;

const VIEW_DATA: IViewData = {
    name: 'MineUI',
    type: EViewType.Panel,
    bundle: EBundleType.Game,
    zIndex: 100,
};

@ccclass
export default class MineUI extends BaseView implements IMessage {

    @property({ type: sp.Skeleton, tooltip: "凿spine动画" })
    private ske: sp.Skeleton = null;
    @property({ type: sp.Skeleton, tooltip: "凿spine动画" })
    private ske2: sp.Skeleton = null;
    @property({ type: cc.Node, tooltip: "圆圈标记" })
    private yuan: cc.Node = null;
    @property({ type: cc.Node, tooltip: "镐子静态图" })
    private gaozi: cc.Node = null;

    @property({ type: cc.Node, tooltip: "收集节点" })
    private collectNode: cc.Node = null;
    @property({ type: cc.Node, tooltip: "收集父节点" })
    private collectItems: cc.Node = null;
    @property({ type: cc.Node, tooltip: "收集子节点" })
    private collectItem: cc.Node = null;
    @property({ type: cc.Node, tooltip: "收购单按钮节点" })
    private btnCollect: cc.Node = null;

    @property({ type: cc.Node, tooltip: "凿一凿弹窗" })
    private zaoNode: cc.Node = null;
    @property({ type: cc.Node, tooltip: "奖励弹窗" })
    private rewardNode: cc.Node = null;
    @property({ type: cc.Node, tooltip: "物品父节点" })
    private items: cc.Node = null;
    @property({ type: cc.Node, tooltip: "物品节点" })
    private item: cc.Node = null;
    @property({ type: cc.Label, tooltip: "价值" })
    private labDesc: cc.Label = null;

    private rewards: { item: IItemConfig, num: number }[] = [];
    private totalPrice: number = 0;

    private gameData: IGameData = null;
    private talkData: ITalkData = null;

    private collects: ICollectConfig = null;

    recvMsg(cmd: number, data: any) {
        switch (cmd) {
            case EventID.TEST_CMD:
                {

                }
                break;
        }
    }

    protected onLoad() {
        super.onLoad();
        this.addMessage(EventID.TEST_CMD, this);

        this.gameData = StorageUtil.instance.getGameData();
        this.talkData = StorageUtil.instance.getTalkData();
        this.collects = GlobalData.getCollectData();

        // 创建收集信息
        this.collectNode.active = false;
        if (this.collects) {
            for (let i = 0; i < this.collects.needs.length; i++) {
                const need = this.collects.needs[i];
                if (need) {
                    const item = cc.instantiate(this.collectItem);
                    item.parent = this.collectItems;
                    item.active = true;
                }
            }
            this.collectNode.active = true;
        }
        const isActive = this.talkData.id === TalkModule.COLLECT_ANIMAL || this.talkData.id === TalkModule.COLLECT_FIVE;
        this.collectNode.active = isActive;
        this.btnCollect.active = isActive;

        this.init();
    }

    private init() {
        this.isHasChild = false;

        this.ske.node.active = false;
        this.ske2.node.active = false;
        this.gaozi.active = true;
        this.yuan.active = false;
        this.zaoNode.active = true;
        this.rewardNode.active = false;

        this.updateCollects();
    }

    private updateCollects() {
        if (!this.collects) return;
        this.collectItems.children.forEach((o, i) => {
            this.updateCollectItem(o, this.collects.needs[i]);
        });
    }

    private updateCollectItem(node: cc.Node, data: { id: number, num: number }) {
        const config = BaseConfig.instance.getItemInfoById(data.id);
        const bagData = GlobalData.getBagDataById(data.id);
        const had = bagData?.num || 0;
        const need = data.num;
        const labName = cc.find('labName', node).getComponent(cc.Label);
        const labHad = cc.find('labHad', node).getComponent(cc.Label);
        const labNeed = cc.find('labNeed', node).getComponent(cc.Label);
        labName.string = `${config.name}`;
        labHad.string = `${had}`;
        labNeed.string = `/${need}`;
        labHad.node.color = cc.color().fromHEX(had >= need ? '#10E302' : '#E90000');
    }

    private getPropInfo(): { ids: number[], chance: number, isCollect: boolean } {
        const info = { ids: [], chance: 100, isCollect: false };
        switch (this.talkData.id) {
            case TalkModule.COLLECT_TIEBAN:         // 铁板
            case TalkModule.COLLECT_ANIMAL:         // 动物符咒
            case TalkModule.COLLECT_FIVE:           // 五行珠
                {
                    const tempArr = [];
                    if (this.collects) {
                        this.collects.needs.forEach((o) => {
                            tempArr.push(o.id);
                        });
                        info.ids = this.need(tempArr);
                        info.chance = this.collects.chance;
                        info.isCollect = true;
                    }
                }
                break;
        }
        return info;
    }

    /**
     * 随机物品
     * 当前任务/商人道具
     * @param propIds 
     */
    /**
     * 随机掉落物品/当前任务或商人需求道具
     * @param drop  掉落区域
     * @param propIds 掉落id数组
     * @param chance 掉落概率
     * @returns 
     */
    private random(drop: EDropType, propIds: number[], chance: number) {
        const items = BaseConfig.instance.getItemInfosByType(drop, EBagType.Item);
        const props: IItemConfig[] = [];
        propIds.forEach((o, i) => {
            const prop = BaseConfig.instance.getItemInfoById(o);
            props.push(prop);
        });

        const p = Math.random() * 100;
        const p1 = propIds.length > 0 ? chance : 0;
        if (p > p1) {
            const item = items[Math.floor(Math.random() * items.length)];
            // console.log("随机物品:", items, item);
            return item;
        } else {
            const prop = props[Math.floor(Math.random() * props.length)];
            // console.log("随机道具:",  props, prop);
            return prop;
        }
    }

    /** 获取任务/商人列表中未拥有 */
    private need(propIds: number[]) {
        for (let i = propIds.length - 1; i > -1; i--) {
            const isHad = this.checkBagHad(propIds[i]);
            if (isHad) {
                propIds.splice(i, 1);
            }
        }
        return propIds;
    }

    public checkBagHad(id: number, value: number = 1) {
        const bagData = StorageUtil.instance.getBagData();
        const data1 = bagData.find((o) => o.id === id);
        const data2 = this.rewards.filter((o) => o.item.id === id);
        const num1 = data1?.num || 0;
        const num2 = data2?.length || 0;
        const total = num1 + num2;
        return total >= value;
    }

    private makeAMine(ratio: number) {
        this.isHasChild = true;
        this.ske.node.active = true;
        this.gaozi.active = false;
        this.yuan.active = true;
        // this.zaoNode.active = false;
        this.rewardNode.active = false;

        // // 设置位置
        // const x = GameUtil.getRandomInteger(-300, 300);
        // const y = GameUtil.getRandomInteger(-465, 621);
        // this.ske.node.setPosition(cc.v2(x, y));
        // // this.ske.node.scaleX = Math.random() > 0.5 ? 1 : -1;

        SceneGame.instance.showTopMask();
        const self = this;
        const data: IBaseSkeData = {
            ske: this.ske,
            animName: `${2}`,
            isLoop: false,
            callback: () => {
                SceneGame.instance.hideTopMask();
                self.showReward(ratio);
            }
        };
        GameUtil.playAnimation(data);

        if (ratio === 5) {
            this.ske2.node.active = true;
            const data: IBaseSkeData = {
                ske: this.ske2,
                animName: `${2}`,
                isLoop: false,
                callback: () => {
                    this.ske2.node.active = false;
                }
            };
            GameUtil.playAnimation(data);
        }
    }

    private showReward(ratio: number) {
        this.ske.node.active = false;
        this.gaozi.active = false;
        this.yuan.active = false;
        // this.zaoNode.active = false;
        this.rewardNode.active = true;

        for (let i = this.items.children.length - 1; i > -1; i--) {
            const item = this.items.children[i];
            item.destroy();
        }

        this.totalPrice = 0;
        this.rewards = [];
        // 五连凿时设置一个必中(从索引1~4中随机, 避免跟凿一凿冲突)
        const mustIndex = GameUtil.getRandomInteger(1, 4);
        for (let i = 0; i < ratio; i++) {
            const info = this.getPropInfo();
            const data = this.random(EDropType.Mine, info.ids, i === mustIndex ? 100 : info.chance);
            // console.log('data:', data);
            const temp = `${data.num}`.split("#");
            const num = GameUtil.getRandomInteger(Number(temp[0]), Number(temp[1])) || Number(temp[0]);
            // console.log('temp:', temp, "num:", num); 
            const item = cc.instantiate(this.item);
            item.parent = this.items;
            item.y = 0;
            item.active = true;
            this.rewards.push({ item: data, num: num });
            this.setItemData(item, data);

            this.totalPrice += data.basePrice;
        }

        this.labDesc.string = `物品价值: ${this.totalPrice}`;
    }

    private setItemData(node: cc.Node, data: IItemConfig) {
        const icon = cc.find("icon", node).getComponent(cc.Sprite);
        const labValue = cc.find("value", node).getComponent(cc.Label);
        const labName = cc.find("name", node).getComponent(cc.Label);
        labValue.string = `${1}`;
        labName.string = `${data.name}`;
        LoadUtil.instance.setSpriteFrame(icon, EResType.Item, data.id, 100, 100);
    }

    private getReward(ratio: number) {
        // 初始化
        this.init();

        // 获得
        this.rewards.forEach((o) => {
            GlobalData.addBagData(o.item.id, ratio);
        });
        // console.log("放入背包:", GlobalData.bagDatas);
        this.updateCollects();
        SceneGame.instance.showToast(cc.v2(0, 0), '物品已放入背包');

        // 任务完成衔接下个剧情
        const info = this.getPropInfo();
        if (info.isCollect && info.ids.length < 1) {
            // 挖到铁板
            if (this.talkData.id === 10204) {
                this.talkData.id++;
            }
        }
    }

    public onCloseChild() {
        if (this.isHasChild) {
            this.isHasChild = false;
            this.getReward(1);
        }
    }

    public onCloseClicked() {
        super.onCloseClicked();
        GameUI.instance.check();
        TownUI.instance.check();
    }

    private onBtnsClicked(event: cc.Event.EventTouch, eventData: string) {
        const name = event.target.name;
        switch (name) {
            case "btnOne":
                {
                    AudioManager.instance.playSound("挖矿1", 0.8);
                    this.makeAMine(1);
                }
                break;
            case "btnFive":
                {
                    // 播放视频
                    AdManager.showVideoAd(() => {
                        AudioManager.instance.playSound("挖矿1", 0.8);
                        this.makeAMine(5);
                    });
                }
                break;
            case "btnReward":
                {
                    this.getReward(1);
                }
                break;
            case "btnDouble":
                {
                    // 播放视频
                    AdManager.showVideoAd(() => {
                        this.getReward(2);
                    });
                }
                break;
            case "btnCollect":      // 收购单
                {
                    if (!this.collects) {
                        SceneGame.instance.showToast(cc.v2(0, 0), '美女商人暂时外出');
                        return;
                    }
                    this.collectNode.active = true;
                }
                break;
            case "btnArrow":        // 箭头  关闭收购单
            case "items":
                {
                    this.collectNode.active = false;
                }
                break;
        }
    }
}
AppService.instance.registViewData(VIEW_DATA);